package mongo

import (
	"context"
	"core/config"
	"github.com/dubbogo/gost/log/logger"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"time"
)

var (
	Config = &MongoConfig{}

	client *mongo.Client
	Db     *mongo.Database
)

func init() {
	config.ConfigViper.UnmarshalKey("mongo", Config)
	if "" == Config.URI {
		return
	}

	var opt = options.Client().ApplyURI(Config.URI).
		SetConnectTimeout(5 * time.Second)

	var MaxPoolSize uint64 = 1000
	opt.MaxPoolSize = &MaxPoolSize

	// 1.连接mongodb
	client, err := mongo.Connect(context.Background(),
		opt)
	if err != nil {
		logger.Warnf("连接mongo失败 %v", err)

	}

	if err = client.Ping(context.Background(), nil); err != nil {
		logger.Warnf("连接mongo失败 %v", err)
		 
	}

	// 由于都是对同一个集合进行操作，所以在初始化mongodb时就选择了集合，防止后续出现大量重复代码
	Db = client.Database(Config.Db)
	logger.Info("连接mongo成功")
}
